package com.nanako.wanxinp2p.consumer.service.impl;

import com.nanako.wanxinp2p.api.account.model.AccountRegisterDTO;
import com.nanako.wanxinp2p.api.consumer.model.ConsumerRegisterDTO;
import com.nanako.wanxinp2p.common.domain.CodePrefixCode;
import com.nanako.wanxinp2p.common.exception.BusinessException;
import com.nanako.wanxinp2p.common.utils.CodeNoUtil;
import com.nanako.wanxinp2p.consumer.agent.AccountFeign;
import com.nanako.wanxinp2p.consumer.common.ConsumerErrorCode;
import com.nanako.wanxinp2p.consumer.entity.Consumer;
import com.nanako.wanxinp2p.consumer.mapper.ConsumerMapper;
import com.nanako.wanxinp2p.consumer.service.IConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.Hmily;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class ConsumerServiceImpl implements IConsumerService {
    @Autowired
    private AccountFeign accountFeign;
    @Autowired
    private ConsumerMapper consumerMapper;

    @Override
    public Integer checkMobile(String mobile) {
        //根据手机号查询用户，存在返回1 不存在返回0
        Consumer consumer = consumerMapper.selectByMobile(mobile);
        return consumer != null ? 1 : 0;
    }

    @Override
    @Hmily(cancelMethod = "cancelRegister", confirmMethod = "confirmRegister")
    @Transactional
    public void register(ConsumerRegisterDTO consumerRegisterDTO) {
        log.info("execute =================>> register");
        //1、检测是否已注册，如果已经注册，则抛出 ConsumerErrorCode.E_140107 异常
        if (checkMobile(consumerRegisterDTO.getMobile()).equals(1)) {
            throw new BusinessException(ConsumerErrorCode.E_140107);
        }
        AccountRegisterDTO accountRegisterDTO = new AccountRegisterDTO();
        BeanUtils.copyProperties(consumerRegisterDTO, accountRegisterDTO);
        //2、如果用户没有注册，则保存该用户数据 到 consumer 表中
        Consumer consumer = new Consumer();
        consumer.setUsername(CodeNoUtil.getNo(CodePrefixCode.CODE_NO_PREFIX));
        consumer.setUserNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX));
        consumer.setIsBindCard(0);
        BeanUtils.copyProperties(consumerRegisterDTO, consumer);
        consumerMapper.saveConsumer(consumer);
        //3、并通过Feign远程调用 统一账号服务 实现 账号的保存
        accountFeign.register(accountRegisterDTO);
    }

    /**
     * 分布式事务tcc：confirm
     */
    @Override
    public void confirmRegister(ConsumerRegisterDTO consumerRegisterDTO){
        log.info("execute =================>> confirmRegister");
    }

    /**
     * 分布式事务tcc：cancel
     */
    @Override
    public void cancelRegister(ConsumerRegisterDTO consumerRegisterDTO){
        log.info("execute =================>> cancelRegister");
        // 删除账号
        consumerMapper.deleteByMobile(consumerRegisterDTO.getMobile());
    }
}
